<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of UserController
 *
 * @author Sebastian
 */
class Admin_UserController extends CMS_Controller_Action
{
    public function init()
    {
        parent::init();
    }

    public function loginAction()
    {
        parent::disableLayout();
        
        $form = $this->getLoginForm();
        $this->view->form = $form;
	    if (!$this->getRequest()->isPost())
        {
            return;
        }
        else
        {
            if (!$form->isValid($_POST))
            {
                $this->view->form = $form;
                return;
            }
            else
            {
                $values = $form->getValues();

                if( MD_User::login($values['login'], md5($values['password'])) )
                {
                    $this->_redirect("/admin/index");
                }
                else
                {
                    $this->view->errorLogin = true;
                    $this->view->form = $form;
                    return;
                }
            }
        }
    }
    /**
     * 
     * @return string
     * Valida si un usuario existe en la base de datos en base a su email.
     */
	public function existsuserAction()
	{
		parent::disableAllViews();
		$request = $this->_request->getParams();
        $email = $request['email']; 
		$exist = MD_User::exists($email);
		
		if ( $exist )
		{
			echo "1";
		}
		else
		{
			echo "0";
		}
		
	}
    public function logoutAction()
    {
        parent::disableAllViews();

        MD_User::logout();

        $this->_redirect("/admin/user/login");
    }

    public function signupAction()
    {
        parent::disableLayout();
        $form = $this->getSignupForm();
        $this->view->form = $form;

        if (!$this->getRequest()->isPost())
        {
            return;
        }
        else
        {
            if (!$form->isValid($_POST))
            {
                $this->view->form = $form;
                return;
            }
            else
            {
                $values = $form->getValues();

                if( MD_User::signup($values['name'], $values['lastname'], $values['email'], $values['password']) )
                {
                    if( MD_User::login($values['email'], md5($values['password'])) )
                    {
                        $this->sendSingupEmail($values['name'], $values['lastname'], $values['email'], $values['password']);
                        $this->_redirect("/system");
                    }
                }
                else
                {
                    $this->view->errorSignup = true;
                    $this->view->form = $form;
                    return;
                }
            }
        }
    }

    public function recoverypasswordAction()
    {
        parent::disableLayout();

        
        $form = $this->getRecoveryPasswordForm();
        $this->view->form = $form;
        $this->view->okRecovery = false;

        if (!$this->getRequest()->isGet())
        {
            return;
        }
        else
        {
		 /*
		  *  Envio de un email al momento de cambiar el password.  
		  */
          $request = $this->_request->getParams();
          $email = $request['email']; 
          	
          $password = MD_User::recoveryPassword($email);
          $this->sendRecoveryPasswordEmail($email,$password);
          $this->view->okRecovery = true;
        }
        
    }

    private function getSignupForm()
    {
        $form = new Zend_Form();
        $form->setAction("/system/user/signup")
             ->setMethod('post')
             ->setAttrib("class", "highgray padding10")
             ->setAttrib("style", "width:300px;");


        $name = $form->createElement('text', 'name');
        $name->addValidator('NotEmpty', true)->setLabel("Nombre")->setRequired(true);

        $lastname = $form->createElement('text', 'lastname');
        $lastname->addValidator('NotEmpty', true)->setLabel("Apellido")->setRequired(true);

        $email = $form->createElement('text', 'email');
        $email->addValidator('emailAddress')->setLabel("E-mail")->setRequired(true);

        $password = $form->createElement('password', 'password');
        $password->addValidator('StringLength', false, array(6))
        ->setLabel("Clave")
         ->setRequired(true);

         $form->addElement($name)
             ->addElement($lastname)
             ->addElement($email)
             ->addElement($password)
             ->addElement('submit', 'add', array('label' => 'Ingresar','class'=>'btoAdd'));

         return $form;
    }
	/**
	 * 
	 * @return string
	 * Retorna un html con el formulario de login.
	 */
    private function getLoginForm()
    {
        $form = new Zend_Form();
		/*
		 * Datos comunes del Form ( accion, metodo, enctype, clase de estilos, etc. ).
		 */
        $form->setAction("/admin/user/login")
             ->setMethod('post')
             ->setAttrib("class", "formLogin");
        /*
         * Campo Login.
         * Tipo, validacion, mensaje de error, etc.
         */     
		$this->view->title = "Login";
        $login = $form->createElement('text', 'login');
        $login->addValidator('NotEmpty')->setLabel($this->view->t->_('USUARIO'))->setRequired(true);
		$login->addErrorMessage($this->view->t->_('Este_campo_es_obligatorio'));        

		 /*
         * Campo Password.
         * Tipo, validacion, mensaje de error, etc.
         */     
		
        $password = $form->createElement('password', 'password');
        $password->addValidator('NotEmpty')
        ->setLabel($this->view->t->_('CONTRASENIA'))
         ->setRequired(true);
		$password->addErrorMessage($this->view->t->_('Este_campo_es_obligatorio'));	
         $form->addElement($login)
             ->addElement($password)
             ->addElement('submit', 'add', array('label' => "Ingresar",'class'=>'ui-state-default ui-corner-all'));

         return $form;
    }

    private function getRecoveryPasswordForm()
    {
        $form = new Zend_Form();
        $form->setAction("/admin/user/recoverypassword")
             ->setMethod('post')
             ->setAttrib("class", "highgray padding10")
             ->setAttrib("style", "width:300px;");

        $email = $form->createElement('text', 'email');
        $email->addValidator('emailAddress')->setLabel("E-mail")->setRequired(true);

        $form->addElement($email)
             ->addElement('submit', 'add', array('label' => 'Enviar','class'=>'btoAdd'));

         return $form;
    }

    public function mailAction()
    {
        $this->disableLayout();
    }

    private function sendSingupEmail($name, $surname, $email, $password)
    {
       $conf = MR_Config::getInstance(MR_INSTANCE_SERVER);

        $this->view->name = $name;
        $this->view->surname = $surname;
        $this->view->email = $email;
        $this->view->password = $password;
        $this->view->webhost = $conf->webhost;

        $body = $this->view->render("/user/mail.phtml");

        $smtpemail = new Common_System_Mail();
        $smtpemail->addTo($email);
        $smtpemail->setFrom($conf->email->from,$conf->email->fromname );
        $smtpemail->setBodyHtml($body,"utf-8");
        $smtpemail->setSubject("Datos de Registro");
        
        $smtpemail->sendUsingSMTP($conf->email->smtp->host, $conf->email->smtp->username, $conf->email->smtp->password);

    }

    private function sendRecoveryPasswordEmail($email, $password)
    {
     	$conf = IO_Config::getInstance(IO_INSTANCE_SERVER);

        $this->view->email = $email;
        $this->view->password = $password;
        $this->view->webhost = $conf->webhost;
		
        $body = $this->view->render("/user/recoverypasswordmail.phtml");
		        
        $smtpemail = new Common_System_Mail();
        $smtpemail->addTo($email);
        $smtpemail->setFrom($conf->email->from,$conf->email->fromname );
        $smtpemail->setBodyHtml($body,"utf-8");
        $smtpemail->setSubject("Nueva clave generada");
		
        $smtpemail->sendUsingSMTP($conf->email->smtp->host, $conf->email->smtp->username, $conf->email->smtp->password);

    }
}
?>